package cn.xo68.boot.job.jdbcstore.impl;

import cn.xo68.boot.job.entity.JobLog;
import cn.xo68.boot.job.jdbcstore.LogStoreService;
import cn.xo68.core.jdbc.JdbcOperate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 日志存储服务实现
 * @author wuxie
 * @date 2018-7-11
 */
public class LogStoreServiceImpl implements LogStoreService {

    private static final Logger logger=LoggerFactory.getLogger(LogStoreServiceImpl.class);

    private static final String inserat_sql="insert into wx_job_log (job_id, schedule_name , job_name , job_group , schedule_instance , begin_time , end_time , job_result ) values (?  , ?  , ?  , ?  , ?  , ? , ? , ? )";
    private static final String updateJob_sql="update wx_job set success_count=success_count+?,fail_count=fail_count+? where job_id=? ";

    private final JdbcOperate jdbcOperate;

    public LogStoreServiceImpl(JdbcOperate jdbcOperate) {
        this.jdbcOperate = jdbcOperate;
    }


    @Transactional(value = "jobTransactionManager", rollbackFor = Exception.class)
    @Override
    public void add(JobLog jobLog) {
        List<Object> insertArgList=new ArrayList<>();
        insertArgList.add(jobLog.getJobId());
        insertArgList.add(jobLog.getScheduleName());

        insertArgList.add(jobLog.getJobName());
        insertArgList.add(jobLog.getJobGroup());
        insertArgList.add(jobLog.getScheduleInstance());
        insertArgList.add(jobLog.getBeginTime());
        insertArgList.add(jobLog.getEndTime());
        insertArgList.add(jobLog.getJobResult());
        jdbcOperate.update(inserat_sql, insertArgList.toArray());

        List<Object> updateArgList=new ArrayList<>();
        updateArgList.add("y".equals(jobLog.getJobResult()) ? 1 : 0);
        updateArgList.add("y".equals(jobLog.getJobResult()) ? 0 : 1);
        updateArgList.add(jobLog.getJobId());
        jdbcOperate.update(updateJob_sql, updateArgList.toArray());
    }
}
